package com.ruoyi.violate.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ExecutorService;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.violate.domain.ProductData;
import com.ruoyi.violate.domain.ViolateTilte;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.ruoyi.violate.mapper.BusinessCounselorMapper;
import com.ruoyi.violate.domain.BusinessCounselor;
import com.ruoyi.violate.service.IBusinessCounselorService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-06-05
 */
@Service
public class BusinessCounselorServiceImpl implements IBusinessCounselorService 
{
    @Autowired
    private BusinessCounselorMapper businessCounselorMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public BusinessCounselor selectBusinessCounselorById(Long id)
    {
        return businessCounselorMapper.selectBusinessCounselorById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param businessCounselor 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<BusinessCounselor> selectBusinessCounselorList(BusinessCounselor businessCounselor)
    {
        return businessCounselorMapper.selectBusinessCounselorList(businessCounselor);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param businessCounselor 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertBusinessCounselor(BusinessCounselor businessCounselor)
    {
        return businessCounselorMapper.insertBusinessCounselor(businessCounselor);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param businessCounselor 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateBusinessCounselor(BusinessCounselor businessCounselor)
    {
        return businessCounselorMapper.updateBusinessCounselor(businessCounselor);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteBusinessCounselorByIds(Long[] ids)
    {
        return businessCounselorMapper.deleteBusinessCounselorByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteBusinessCounselorById(Long id)
    {
        return businessCounselorMapper.deleteBusinessCounselorById(id);
    }

    /**
     * 导入数据
     * @param filePath
     * @return
     */
    @Override
    public int importFile(String filePath) throws IOException {

        ExecutorService executor = ThreadUtil.newExecutor(5);

        executor.execute(() ->{
            String path = RuoYiConfig.getProfile() + filePath.substring(8, filePath.length());
            System.out.println(path);

            File file = new File(path);
            MultipartFile files = getMultipartFile(file);
            ExcelReader reader = null;
            try {
                reader = ExcelUtil.getReader(files.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            reader.addHeaderAlias("店铺名", "shopName");
            reader.addHeaderAlias("统计日期", "statisticsDate");
            reader.addHeaderAlias("商品ID", "productId");
            reader.addHeaderAlias("商品名称", "productName");
            reader.addHeaderAlias("下单件数", "productVisitors");
            reader.addHeaderAlias("商品加购件数", "productAdds");
            //获取所有的Excel表格中的tilte
            List<BusinessCounselor> list = reader.readAll(BusinessCounselor.class);

//            List<ProductData> list = new ArrayList<ProductData>();
//            EasyExcel.read(path, ProductData.class, new PageReadListener<ProductData>(dataList -> {
//                for (ProductData productData : dataList) {
//                    log.info("读取到一条数据{}", JSON.toJSONString(productData));
//                    list.add(productData) ;
//                }
//            })).sheet().doRead();

            String id = IdUtils.simpleUUID() ;
            String[] split = filePath.split("/");
            String shopName = split[6].split("生意参谋")[0] ;

            //关闭线程
            for(BusinessCounselor entity :list){
                entity.setShopName(shopName);
                //在数据库中violate_tilte表中添加tilte数据
                this.insertBusinessCounselor(entity);
            }
            System.out.println("结束线程");
            executor.shutdown();
        });
        return 1 ;
    }

    public MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName()
                , (int) file.length()
                , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

    /**
     * 导出数据
     * @param response
     * @param \
     */
    public void export(HttpServletResponse response, BusinessCounselor businessCounselor) throws Exception {
        List<BusinessCounselor> list = this.selectBusinessCounselorList(businessCounselor);


//        ExcelUtil<ViolateTilte> util = new ExcelUtil<ViolateTilte>(ViolateTilte.class);
//        util.exportExcel(response, list, "标题数据");

//        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
//        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //过滤后的数据，保存为excel表格
        Set<String> includeColumnFiledNames = new HashSet<String>();
        includeColumnFiledNames.add("shopName");
        includeColumnFiledNames.add("statisticsDate");
        includeColumnFiledNames.add("productId");
        includeColumnFiledNames.add("productName");
        includeColumnFiledNames.add("commodityPrice");
        includeColumnFiledNames.add("productVisitors");
        includeColumnFiledNames.add("productAdds");
//        EasyExcel.write(response.getOutputStream(), ViolateTilte.class).includeColumnFiledNames(includeColumnFiledNames).sheet("标题数据").doWrite(list);
        // EasyExcelUtil.writeExcel(response, list, "标题数据", ViolateTilte.class);

        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), BusinessCounselor.class).build() ;

        //访客数不为零
//        Set<BusinessCounselor> list1 = new TreeSet<>(Comparator.comparing(BusinessCounselor::getProductId));
        ArrayList<BusinessCounselor> list1 = new ArrayList<>();
        //商品加购数
//        Set<BusinessCounselor> list2 = new TreeSet<>(Comparator.comparing(BusinessCounselor::getProductId));
        ArrayList<BusinessCounselor> list2 = new ArrayList<>();
        //去重后的数据
        Set<BusinessCounselor> list3 = new TreeSet<>(Comparator.comparing(BusinessCounselor::getProductId));
//        ArrayList<BusinessCounselor> list3 = new ArrayList<>();


        for (BusinessCounselor pro : list) {
            System.out.println(pro.toString());
            if (StringUtils.isEmpty(pro.getProductVisitors()) || StringUtils.isEmpty(pro.getProductAdds()) ){
                list.remove(pro) ;
                continue;
            }
            if (!pro.getProductVisitors().equals("0")){
                list1.add(pro) ;
            }
            if (!pro.getProductAdds().equals("0")){
                list2.add(pro);
            }
            if (!pro.getProductAdds().equals("0") || !pro.getProductVisitors().equals("0")){
                list3.add(pro) ;
            }
        }

        WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "总表").build() ;
        excelWriter.write(list, writeSheet1);

        WriteSheet writeSheet2 = EasyExcel.writerSheet(2, "下单件数不为零").build() ;
        excelWriter.write(list1, writeSheet2);

        WriteSheet writeSheet3 = EasyExcel.writerSheet(3, "商品加购数不为零").build() ;
        excelWriter.write(list2, writeSheet3);

        WriteSheet writeSheet4 = EasyExcel.writerSheet(4, "去重后的数据").build() ;
        excelWriter.write(list3, writeSheet4);

        excelWriter.finish();
        response.flushBuffer();
    }
}
